package com.benben.springSecurity.controller;

import com.benben.springSecurity.entity.User;
import com.benben.springSecurity.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes({"user","username"})
public class UserController {

    @Autowired
    UserServiceImpl us;

    @RequestMapping("/login")
    public ModelAndView login(User user, ModelMap model){
        User userInDb = us.findUserByName(user.getUsername());
        ModelAndView mv = new ModelAndView();
        if(userInDb!=null){
            if(userInDb.getUsername().equals(user.getUsername())&&userInDb.getPassword().equals(user.getPassword())){
                mv.setViewName("success");
                return mv;
            }
        }
        mv.setViewName("false");
        model.addAttribute("username",user.getUsername());
        return mv;
    }

    @RequestMapping(method=RequestMethod.GET,value="/index")
    public String index(){
        return "index";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    private ModelAndView addUser(User user){
        us.saveUser(user);
        ModelAndView mv = new ModelAndView();
        mv.setViewName("success");
        return mv;
    }


    @RequestMapping(value = "/success",method = RequestMethod.GET)
    private String success(User user){
        return "success";
    }

    @RequestMapping(value = "/false",method = RequestMethod.GET)
    private String false1(User user){
        us.saveUser(user);
        return "false";
    }
}
